package com.enze.encryptionanddecryption.JiaMi;

/**
 * @Author TacoMan
 * @Date 2023/6/12 11:01
 * @Version 1.0
 */
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Slf4j
public class AESSecret {

    // 加密
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            return null;
        }
        if (sKey.length() != 16) {
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return Base64.getMimeEncoder().encodeToString(encrypted);
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            if (sKey == null) {
                return null;
            }
            if (sKey.length() != 16) {
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//数据块128位，
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            Base64.Decoder decoder=Base64.getMimeDecoder();
            byte[] encrypted1 = decoder.decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                return null;
            }
        } catch (Exception ex) {
            return null;
        }
    }

    public static void main(String[] args) throws Exception {

        String cKey = "odjnehakduchwkdu";
        // 需要加密的字串
        String cSrc = "辽宁税务123456";
        System.out.println("需要加密的字串:"+cSrc);
        // 加密
        String enString = AESSecret.Encrypt(cSrc, cKey);
        System.out.println("加密后的字串是：" + enString);

        // 解密
        String DeString = AESSecret.Decrypt(enString, cKey);
        System.out.println("解密后的字串是：" + DeString);
    }
}
